﻿namespace Blaze.Framework
{
    using System.Collections;
    using UnityEngine;
    using UnityEngine.Assertions;
    using UnityEngine.SceneManagement;

    /// <summary>
    /// 自定义游戏闪屏配置。
    /// </summary>
    public class SplashScreen : MonoBehaviour
    {
        /// <summary>
        /// 设置闪屏的时间。
        /// </summary>
        public float Duration;

        /// <summary>
        /// 获取闪屏所使用的场景名称。
        /// </summary>
        public const string SceneName = "SplashScreen";

        /// <summary>
        /// 获取闪屏的唯一实例。
        /// </summary>
        public static SplashScreen Instance { get; private set; }

        /// <summary>
        /// 获取一个值，表示闪屏是否进入了可跳过的状态。
        /// </summary>
        public bool IsSkippable
        {
            get { return mIsMarkedSkippable || Time.time - mBeginTime > Duration; }
        }

        /// <summary>
        /// 初始化闪屏，在下一帧可以通过<see cref="Instance"/>获取实例。
        /// </summary>
        public static void Initialize()
        {
            CoroutineManager.StartNew(init());
        }

        /// <summary>
        /// 销毁闪屏以及其所占用的资源。
        /// </summary>
        public void Dispose()
        {
            SceneManager.UnloadSceneAsync(mScene);
            Instance = null;
        }

        /// <summary>
        /// 设置闪屏已可以跳过了。
        /// </summary>
        public void MarkAsSkippable()
        {
            mIsMarkedSkippable = true;
        }

        protected void Start()
        {
            mBeginTime = Time.time;
        }

        private static IEnumerator init()
        {
            SceneManager.LoadScene(SceneName, LoadSceneMode.Additive);
            yield return null;
            var scene = SceneManager.GetSceneByName(SceneName);
            Assert.IsTrue(scene.isLoaded);
            Assert.IsTrue(scene.IsValid());
            Instance = FindObjectOfType<SplashScreen>();
            Assert.IsNotNull(Instance, "在闪屏场景内找不到SplashScreen组件");
            Instance.mScene = scene;
        }

        private float mBeginTime;
        private bool mIsMarkedSkippable;
        private Scene mScene;
    }
}